package com.example.paper.mvp.model;

import com.example.mvp.model.BaseEntity;
import com.example.mvp.model.BaseModel;
import com.example.paper.api.Api;
import com.example.paper.brean.ChannelBean;
import com.example.paper.brean.HttpCode;
import com.example.paper.brean.ImageBannerBean;
import com.example.paper.brean.NewsBean;
import com.example.paper.brean.TextBannerBean;
import com.example.paper.http.factory.ChangeFunction;
import com.example.paper.http.factory.HttpFactory;
import com.example.paper.http.factory.HttpType;
import com.example.paper.mvp.contract.LREContract;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;

public class LREModel extends BaseModel implements LREContract.ILREModel {

    @Override
    public Observable<BaseEntity> requestAll(Map<String, Object>... maps) {
        //根据传递进来的maps  数量创建生成专门用来存放被观察者的集合
        List<Observable<BaseEntity>> observables = new ArrayList<>();
        for (int i = 0; i < maps.length; i++) {
            Map<String, Object> map = maps[i];
            observables.add(change2BaseEntity(map));
        }
        return Observable.merge(observables);
    }

    //异步任务转化为BaseEntity任务
    private Observable<BaseEntity> change2BaseEntity(Map<String, Object> map) {
        int code = (int) map.get("code");
        map.remove("code");
        Observable<BaseEntity> ob = null;
        switch (code) {
            case HttpCode.USERCHANNELCODE:
                //获取首页用户频道接口
                ob = HttpFactory.getInstance().factory(HttpType.TOKENSIGNTYPE)
                        .getRetrofit().create(Api.class)
                        .requestUserChannels(createBody(map))
                        .map(new ChangeFunction<ChannelBean>());
                break;
            case HttpCode.CHANNELNEWS:
                //按频道获取新闻列表接口
                ob = HttpFactory.getInstance().factory(HttpType.TOKENSIGNTYPE)
                        .getRetrofit().create(Api.class)
                        .requestNews(createBody(map))
                        .map(new ChangeFunction<NewsBean>());
                break;
            case HttpCode.IMAGERBANNERCODE:
                ob = HttpFactory.getInstance().factory(HttpType.TOKEN)
                        .getRetrofit().create(Api.class)
                        .requestUserImageBanner().map(new ChangeFunction<ImageBannerBean>());
                break;
            case HttpCode.TEXTBANNERCODE:
                ob = HttpFactory.getInstance().factory(HttpType.TOKEN)
                        .getRetrofit().create(Api.class)
                        .requestTextBanner().map(new ChangeFunction<TextBannerBean>());
                break;
        }
        return ob;
    }


    @Override
    public Observable<BaseEntity> request_refresh_load(Map<String, Object> map) {
        return change2BaseEntity(map);
    }
}
